package com.tarena.lbs.marketing.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.api.AdminApi;
import com.tarena.lbs.common.marketing.enums.MarketingResultEnum;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.marketing.web.repository.ActivityRepository;
import com.tarena.lbs.marketing.web.repository.CouponRepository;
import com.tarena.lbs.pojo.attach.dto.AttachDTO;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.attach.query.AttachQuery;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.marketing.param.ActivityParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import com.tarena.lbs.pojo.marketing.query.ActivityQuery;
import com.tarena.lbs.pojo.marketing.vo.ActivityVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ActivitiService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private AdminApi adminApi;
    @DubboReference
    private AttachApi attachApi;
    @Autowired private CouponRepository couponRepository;

    public PageResult<ActivityVO> activityPage(ActivityQuery query) throws BusinessException {
        UserPrinciple userPrinciple = getUserPrinciple();
        AdminDTO adminDetail = adminApi.getAdminDetail(userPrinciple.getId());
        Asserts.isTrue(adminDetail==null,new BusinessException(MarketingResultEnum.ADMIN_NOT_FOUND));
        Asserts.isTrue(userPrinciple.getRole()!= Roles.SHOP,new BusinessException("-2","用户权限不足"));
        query.setBusinessId(adminDetail.getBusinessId());
        PageInfo<ActivityPO> poPageInfo=activityRepository.getActivitiesByPage(query);
        PageResult<ActivityVO> voPages=new PageResult<>();
        voPages.setPageNo(poPageInfo.getPageNum());
        voPages.setPageSize(poPageInfo.getPageSize());
        voPages.setTotal(poPageInfo.getTotal());
        List<ActivityVO> vos=null;
        if (poPageInfo.getTotal()>0){
            vos=poPageInfo.getList().stream().map(po->{
                ActivityVO vo=new ActivityVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPages.setObjects(vos);
        return voPages;
    }
    private UserPrinciple getUserPrinciple() throws BusinessException {
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        if (userPrinciple == null){
            throw new BusinessException("101","用户认证解析失败");
        }
        return userPrinciple;
    }
    @Transactional(rollbackFor = Exception.class)
    public void activitySave(ActivityParam param) throws BusinessException, ParseException {
        //1.活动绑定businessId 需要认证
        UserPrinciple userPrinciple = getUserPrinciple();
        Asserts.isTrue(userPrinciple.getRole()!=Roles.SHOP,new BusinessException("-2","用户权限不足"));
        //2.拿到用户id 查询admin详情
        AdminDTO adminDetail = adminApi.getAdminDetail(userPrinciple.getId());
        Asserts.isTrue(adminDetail==null,new BusinessException(MarketingResultEnum.ADMIN_NOT_FOUND));
        param.setBusinessId(adminDetail.getBusinessId());
        //3.创建写入数据库的po 拷贝已有参数
        ActivityPO poParam=new ActivityPO();
        BeanUtils.copyProperties(param,poParam);
        //4.补充数据 时间 状态 和开启状态 奖励类型1 增领 2 满减 3折扣 4 秒杀 5 抽奖
        //起始时间 结束时间 转化 封装date
        poParam.setCreateAt(new Date());
        poParam.setUpdateAt(poParam.getCreateAt());
        poParam.setStatus(0);
        poParam.setEnableStatus(0);
        poParam.setRewardType(1);
        poParam.setStartDate(DateUtils.parseDate(param.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
        poParam.setEndDate(DateUtils.parseDate(param.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
        //5.保存到数据库
        activityRepository.saveActivity(poParam);
        //6.使用图片服务 绑定图片数据
        String imgIds = param.getImgIds();//157,158,159 activityId=业务id businessType=500
        //封装一个绑定图片的方法
        bindPictures(imgIds,poParam.getId(),500);
    }

    private void bindPictures(String imgIds, Integer businessId, int businessType) throws BusinessException {
        String[] imgids = imgIds.split(",");
        List<PicUpdateParam> picParams=new ArrayList<>();
        if (imgids!=null&&imgids.length>0){
            for (String imgid : imgids) {
                Integer id=Integer.valueOf(imgid);
                PicUpdateParam param=new PicUpdateParam();
                param.setBusinessId(businessId);
                param.setBusinessType(businessType);
                param.setId(id);
                picParams.add(param);
            }
            attachApi.batchUpdateBusiness(picParams);
        }else{
            throw new BusinessException("-2","图片是空,还绑定什么");
        }
    }
    //不同环境url图片地址 前缀不一样
    @Value("${url.image.prefix}")
    private String urlPrefix;
    public ActivityVO activityDetail(Integer id) throws BusinessException {
        ActivityVO vo=new ActivityVO();
        //1.查询本地数据库表格activity
        ActivityPO po=activityRepository.getActivityById(id);
        Asserts.isTrue(po==null,new BusinessException("-2","不存在活动信息"));
        BeanUtils.copyProperties(po,vo);
        //2.根据完整数据记录的imgIds 解析读取图片拼接url
        //从po拿到当初创建活动图片id信息 128,129,130
        //String[] imgIds = po.getImgIds().split(",");
        //利用图片ids 查询每张图片的fileUuid
        //封装AttachQuery查询入参
        AttachQuery query=new AttachQuery();//bizId bizType
        query.setBusinessId(po.getId());
        query.setBusinessType(500);
        List<AttachDTO> attachDtos = attachApi.getAttachInfoByParam(query);
        //某一个业务可能绑定图片是多张 只用到每个图片fileUuid
        //在图片非空时,将图片fileUuid拿出来拼接url 形成多张图片url地址
        if (CollectionUtils.isNotEmpty(attachDtos)){
            List<String> imgPics=attachDtos.stream().map(dto->{
                String fileUuid = dto.getFileUuid();
                String url=urlPrefix+fileUuid;
                return url;
            }).collect(Collectors.toList());
            vo.setImgPics(imgPics);
        }
        return vo;
    }
}
